package when3meet.controller;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;

import when3meet.utilities.InputUtilities;
import when3meet.utilities.SpringUtilities;
import when3meet.view.CreateEventFrame;

/**
 * GUI-based controller, handle action when the event mode is selected as
 * closed- a new frame generated for moderator to add the choices
 * 
 * @author Xi
 * 
 */
public class CloseEventRadioBtnController implements ActionListener {

	CreateEventFrame createEventFrame;
	JButton submitBtn;
	static JFrame addChoiceFrame;
	String[] choices;
	JTextField[] textFields;

	public CloseEventRadioBtnController(CreateEventFrame cef) {
		createEventFrame = cef;
	}

	public void actionPerformed(ActionEvent e) {

		JTextField tf = createEventFrame.getMaxChoiceField();

		boolean b = InputUtilities.checkIntegerInput(tf);
		if (b == false) {
			tf.setBackground(Color.RED);
			createEventFrame.getOpenEventRBtn().doClick();
		} else {
			tf.setBackground(Color.WHITE);
		}

		if (b == true) {

			addChoiceFrame = getInstance();
			addChoiceFrame.setVisible(true);
			addChoiceFrame.setLocationRelativeTo(createEventFrame);

			JPanel p = new JPanel(new SpringLayout());
			addChoiceFrame.add(p);

			int maxChoiceNum = Integer.parseInt(tf.getText());
			textFields = new JTextField[maxChoiceNum];

			for (int i = 0; i < maxChoiceNum; i++) {

				JLabel l = new JLabel("Choice " + (i + 1) + ":", JLabel.TRAILING);
				p.add(l);
				JTextField textField = new JTextField(10);
				l.setLabelFor(textField);
				p.add(textField);
				textFields[i] = textField;

			}
			p.add(new JLabel(""));
			submitBtn = new JButton("submit");

			// bind action to submit button, add the choice info to create event
			// frame

			submitBtn.addActionListener(new AddCloseEventChoiceBtnController(this));

			p.add(submitBtn);

			SpringUtilities.makeCompactGrid(p, maxChoiceNum + 1, 2, // rows,
																	// cols
					6, 6, // initX, initY
					6, 6); // xPad, yPad

			((JFrame) p.getTopLevelAncestor()).pack();
		}
	}

	public String[] getChoices() {
		JTextField tf = createEventFrame.getMaxChoiceField();
		int maxChoiceNum = Integer.parseInt(tf.getText());
		choices = new String[maxChoiceNum];
		for (int i = 0; i < maxChoiceNum; i++) {
			String s = textFields[i].getText();
			choices[i] = s;
		}
		return choices;
	}

	public static JFrame getInstance() {
		if (addChoiceFrame == null || addChoiceFrame.equals(null)) {
			addChoiceFrame = new JFrame();
		}
		return addChoiceFrame;
	}

	public static void disposeFrame() {
		getInstance().dispose();
	}
}
